<?php

namespace app\admins\controller;

class Menus extends Base
{
    // Curd复用
    use Curd;

    // 初始化
    protected function initialize()
    {
        parent::initialize();
        $this->model = $this->admin_menu;
        $this->sort = ['ord' => 'desc', 'id' => 'asc'];
        $this->is_page = false;
        $this->rule = [
            'title|菜单名称' => 'require|token|unique:admin_menu', // 验证令牌且值唯一
            'controller|控制器' => 'require|alphaDash',
            'action|方法' => 'requireWith:action|alphaDash',
            'ord|排序' => 'require|integer',
            'ishidden|隐藏' => 'require|in:0,1',
            'status|状态' => 'require|in:0,1'
        ];

        // 下拉菜单树
        if (in_array($this->action, ['add', 'edit'])) {
            if ($this->action == 'add') {
                $id = $this->request->get('id', 0);
                $this->app->view->assign('default', $id);
            }
            $this->app->view->assign('selectTree', $this->selectTree());
        }
    }

    // 列表，json数据重写
    public function index()
    {
        if ($this->request->isAjax()) {
            $list = $this->model->order($this->sort)->select()->toArray();
            $data = $this->datas($list);
            return json($data);
        }
        return $this->app->view->fetch();
    }

    // 删除存在层级，重写方法
    public function del()
    {
        $param = $this->param;
        $row = $this->model->whereIn('id', (array)$param['id'])->select();
        $row->isEmpty() && $this->errMsg(1, '数据不存在');
        $check = $this->admin_menu->whereIn('pid', (array)$param['id'])->count();
        $check && $this->errMsg(1, '请先删除子菜单');
        try {
            // $delete = $row->delete();
            $delete = 1;
        } catch (\Exception $e) {
            $this->errMsg(1, $e->getMessage());
        }
        $delete ? $this->errMsg(0, '删除成功') : $this->errMsg(1, '删除失败');
    }

    // 数据处理
    private function datas($datas)
    {
        $datas = $this->trees($datas); // It is also do`not to set
        $datas = array_map(function ($item) use($datas) { // It is also do`not to set
            $item['title'] = $item['level'] && !array_filter($datas, function($ele) use($item) {
                return $ele['pid'] == $item['id'];
            }) ? "├ " . $item['title'] : $item['title'];
            return $item;
        }, $datas);
        return $datas;
    }

    // 下拉菜单树
    private function selectTree()
    {
        $menus = $this->admin_menu->field('id, pid, title')->order(['ord' => 'desc', 'id' => 'asc'])->select();
        $menus = $this->trees($menus);
        $menus = array_reduce($menus, function ($res, $next) {
            $res[$next['id']] = $next['level'] ? str_repeat("&nbsp;&nbsp;&nbsp;", $next['level']) . "├ " . $next['title'] : $next['title'];
            return $res;
        }, [0 => '&mdash; 顶级菜单 &mdash;']);
        return $menus;
    }
}
